package cn.itsource.pethome.Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.List;

@Component
public class EmailUtil {

    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String sendEmailAddress;


    public void send(String Subject,String text ,String setTo){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //设置发送人
        mailMessage.setFrom(sendEmailAddress);
        //邮件主题
        mailMessage.setSubject(Subject);
        //邮件内容
        mailMessage.setText(text);
        //收件人
        mailMessage.setTo(setTo);

        javaMailSender.send(mailMessage);
    }
    public void sendMime(String Subject, String content , String setTo, List<File> fileList){


        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper=null;
        try {
            //发送复杂邮件的工具类
            mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            mimeMessageHelper.setFrom(sendEmailAddress);
            mimeMessageHelper.setTo(setTo);
            mimeMessageHelper.setSubject(Subject);
            //第二个参数 true 代表是否是一个html内容
            mimeMessageHelper.setText(content,true);//true 申明是一个html类型
            //添加附件
            if (!CollectionUtils.isEmpty(fileList)){
                for (int i = 0; i < fileList.size(); i++) {
                    File file=fileList.get(i);
                    mimeMessageHelper.addAttachment(file.getName(),file);
                }

            }
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
